package cn.elead.it.sso.system.service.impl;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gitee.elead.api.ApiUtils;
import com.gitee.elead.model.serializer.IUserJsonSerializerService;
import com.gitee.elead.mybatisplus.service.BaseServiceImpl;
import com.gitee.elead.mybatisplus.util.EnumUtil;
import com.gitee.elead.util.ChineseToSpell;

import cn.elead.it.sso.core.util.RSAUtil;
import cn.elead.it.sso.system.dao.IUserDao;
import cn.elead.it.sso.system.emuns.UserStatusEnum;
import cn.elead.it.sso.system.model.User;
import cn.elead.it.sso.system.model.UserAvatar;
import cn.elead.it.sso.system.service.IUserAvatarService;
import cn.elead.it.sso.system.service.IUserService;
import cn.elead.it.sso.system.util.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

/**
 * <p>
 * 用户信息服务类
 * </p>
 *
 * @author luopeng
 */
@Service
public class UserService extends BaseServiceImpl<IUserDao, User> implements IUserService, IUserJsonSerializerService {

	@Value("${file.avatar:d:\\eladmin\\avatar\\}")
	private String avatar;

	@Value("${file.host:http://sso.e-lead.cn/sso/avatar/}")
	private String host;
	
	@Value("${ras.privateKey}")
	private String privateKey;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private IUserAvatarService userAvatarService;

	@Autowired
	private IUserDao userDao;

	public IPage<User> findPageList(Page<User> page, User user) {
		return userDao.findPageList(page, user);
	}

	/**
	 * 根据id获取用户名称
	 */
	@Override
	@Cacheable(cacheNames = "user", key = "#uid")
	public String getUserName(String uid) {
		User user = getById(uid);
		if (ObjectUtils.isEmpty(user)) {
			return uid;
		}
		return user.getUserName();
	}

	/**
	 * 用户登录
	 * 
	 * @param loginName
	 * @param password
	 * @return
	 */
	public User findUser(String loginName) {
		User user = query().eq(User::getAccount, loginName).or() // 账号
				.eq(User::getId, loginName).or() // 工号
				.eq(User::getUserName, loginName) // 姓名
				.getOne();
		return user;
	}

	/**
	 * 定时同步用户
	 */
	@Override
	@Transactional
	public void syncUser() {

		HttpHeaders headers = new HttpHeaders();// header参数
		headers.add("username", "sso");
		headers.add("password", "sso");
		headers.setContentType(MediaType.APPLICATION_JSON);

		HttpEntity<Void> request = new HttpEntity<>(headers); // 组装

		String url = "http://oa.e-lead.cn:8090/timesheet/outer/usersSSO";

		ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, request, JSONObject.class);

		if (response.getStatusCode() == HttpStatus.OK) {

			JSONObject body = response.getBody();

			JSONArray datas = body.getJSONArray("data");

			Iterator<Object> iterator = datas.iterator();

			while (iterator.hasNext()) {
				JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(iterator.next()));
				User user = new User();
				String id = data.getString("work_no");
				if (StringUtils.isBlank(id)) {
					System.err.println(data);
				}
				user.setId(data.getString("work_no"));
				user.setUserId(data.getString("work_no"));
				user.setUserName(data.getString("name"));
				user.setPinYin(ChineseToSpell.getPingYin(data.getString("name")));
				user.setCardId(data.getString("id_card"));
				user.setStatus(EnumUtil.valueOf(UserStatusEnum.class, data.getInteger("state")));
				user.setAccount(data.getString("account"));
				user.setType(0);
				user.setEntryDate(data.getDate("entry_date"));
				user.setLeaveDate(data.getDate("leave_date"));
				user.setDepartment(data.getString("department"));
				user.setCreatedTime(LocalDateTime.now());
				user.setUpdatedTime(LocalDateTime.now());
				User entity = this.getById(user.getId());
				if (Objects.nonNull(entity)) {
					user.setCreatedTime(null);
					if (user.getStatus() == entity.getStatus()) {
						continue;
					}
					user.setPasswordStatus(entity.getPasswordStatus());
					updateById(user);
				} else {
					save(user);
				}
			}
		}
	}

	/**
	 * 初始密码
	 * @throws Exception 
	 */
	@Override
	@Transactional
	public void initPassword() throws Exception {

		List<User> users = query() // 查询
				.eq(User::getPasswordStatus, 0) // 只初始化没有修改密码的
				.between(User::getUpdatedTime, LocalDateTime.now().minusDays(3), LocalDateTime.now().plusDays(1)) // 今天
				.list();
		for (User user : users) {
			String cardId = user.getCardId();
			String last = StringUtils.substring(cardId, 12, 18);
			if(StringUtils.isBlank(last)) {
				last = "123456";
			}
			//String password = Md5Crypt.apr1Crypt(last, user.getId()); // 初始化密码身份证后六位
			String password = RSAUtil.encryptByPrivateKey(last, privateKey);
			update().set(User::getPassword, password).eq(User::getId, user.getId()).execute();
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateAvatar(MultipartFile multipartFile) {

		String oldPath = "";
		User user = getById(ApiUtils.currentUid());
		File file = FileUtil.upload(multipartFile, avatar, user.getUserId());

		String avatarId = user.getAvatar();
		if (StrUtil.isNotBlank(avatarId)) {
			// 获取现在头像
			UserAvatar userAvatar = userAvatarService.getById(avatarId);
			if (userAvatar != null) {
				oldPath = userAvatar.getPath();
			}
			// 更新
			userAvatarService.update().set(UserAvatar::getPath, file.getPath())
					.set(UserAvatar::getRealName, file.getName())
					.set(UserAvatar::getSize, FileUtil.getSize(multipartFile.getSize()))
					.set(UserAvatar::getUrl, host + file.getName()).eq(UserAvatar::getId, avatarId).execute();
		} else {
			// 新增
			avatarId = IdUtil.simpleUUID();
			UserAvatar userAvatar = new UserAvatar();
			userAvatar.setId(avatarId);
			userAvatar.setRealName(file.getName());
			userAvatar.setPath(file.getPath());
			userAvatar.setSize(FileUtil.getSize(multipartFile.getSize()));
			userAvatar.setUrl(host + file.getName());
			userAvatarService.save(userAvatar);
		}
		update().set(User::getAvatar, avatarId).eq(User::getId, user.getId()).execute();

		// 删除旧头像文件
		if (StringUtils.isNotBlank(oldPath)) {
			FileUtil.del(oldPath);
		}
	}
}
